import Vue from "vue";
import App from "./App.vue";
import router from "./router";
import store from "./store";
import "./element";
import { Message } from "element-ui";
import "element-ui/lib/theme-chalk/index.css";
import axios from "axios";
import "./common/css/index.scss";
import filters from "./utils/filter";
import PageTable from "./components/PageTable/PageTable";

Vue.config.productionTip = false;

let flag = true;

Object.keys(filters).forEach(k => Vue.filter(k, filters[k]));

Vue.component("page-table", PageTable);

router.beforeEach(async (to, from, next) => {
  if (flag) {
    const {
      data: { errno, data }
    } = await axios.post("/api/user/isLogin");
    if (!errno) {
      store.commit("setIsLogin", true);
      store.commit("setUsers", data);
    }
    flag = false;
  }
  if (
    to.path.toLowerCase() === "/login" ||
    to.path.toLowerCase() === "/register"
  ) {
    next();
    return;
  }
  if (store.state.isLogin) {
    if (!store.state.menus.length) {
      axios.get("/api/menu/menu").then(({ data: { errno, message, data } }) => {
        if (!errno) {
          store.commit("setMenus", data);
          if (
            data.some(item => item.href.toLowerCase() === to.path.toLowerCase())
          ) {
            next();
            return;
          } else {
            Message({ type: "error", message: "你没有权限访问" });
            next({ path: "/login" });
            return;
          }
        } else {
          Message({ type: "error", message });
          next({ path: "/login" });
          return;
        }
      });
    } else {
      if (
        store.state.menus.some(
          item => item.href.toLowerCase() === to.path.toLowerCase()
        )
      ) {
        next();
        return;
      } else {
        Message({ type: "error", message: "你没有权限访问" });
        next({ path: "/login" });
        return;
      }
    }
  } else {
    next({ path: "/login" });
    Message({ type: "error", message: "你没有权限访问" });
    return;
  }
});

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount("#app");
